package com.gaogzhen.designPattern.twoPhraseTermination;

import java.lang.ref.WeakReference;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Administrator
 * @version 1.0
 * @description 终止标志
 * @date 2022-10-05 11:15
 */
public class TerminationToken {
    public final AtomicInteger reservations = new AtomicInteger(0);

    protected volatile boolean isShutdown = false;

    private final Queue<WeakReference<Terminatable>> coordinatedThreads;

    public TerminationToken() {
        this.coordinatedThreads = new ConcurrentLinkedDeque<WeakReference<Terminatable>>();
    }

    public boolean isToShutdown() { return this.isShutdown; }

    protected void setShutdown(boolean isShutdown) { this.isShutdown = isShutdown;}

    protected void register(Terminatable thread) {
        coordinatedThreads.add(new WeakReference<Terminatable>(thread));
    }

    protected void notifyThreadTermination(Terminatable thread) {
        WeakReference<Terminatable> wrThread;
        Terminatable otherThead;
        while (null != (wrThread = coordinatedThreads.poll())) {
            otherThead = wrThread.get();
            if (null != otherThead && otherThead != thread) {
                otherThead.terminate();
            }
        }
    }

}
